﻿Imports System.Data
Imports Microsoft.Reporting.WebForms
Imports System.Collections.Generic
Imports System.IO
Imports Microsoft.SharePoint
Partial Class ImprimirActas
    Inherits System.Web.UI.Page
    Dim IDACTASharepoint As String
    Dim idActa As Integer
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'verificamos si existe el usuario
        'If verificarPermisos() = False Then
        '    ShowPdf1.Visible = False
        '    Return
        'End If

        If (Page.IsPostBack = False) Then
            IDACTASharepoint = Request.QueryString("ID")
            'lblShareidActa.Text = IDACTASharepoint
            If IDACTASharepoint <> "" Then
                'idActa = IDACTASharepoint
                Dim ruta As String = String.Empty
                Dim nombre As String = String.Empty
                'declaracion del reporte 
                Try

                    'idActa = 14
                    idActa = obtenerCodigo(IDACTASharepoint)
                    'idActa = 106
                    'idActa = IDACTASharepoint
                    ruta = Server.MapPath("~/OutPut/")
                    nombre = "output" & idActa.ToString() & ".pdf"

                    Dim taActa As New dtsReporteActasTableAdapters.sp_listar_ActaxActa_reporteTableAdapter
                    Dim taAsistente As New dtsReporteActasTableAdapters.sp_listar_AsistentesxActa_ReporteTableAdapter
                    Dim taAgenda As New dtsReporteActasTableAdapters.sp_listar_AgendaxActa_ReporteTableAdapter
                    Dim taDesarrolloAgenda As New dtsReporteActasTableAdapters.sp_listar_DesarrolloAgendaxActa_ReporteTableAdapter
                    Dim taAcuerdo As New dtsReporteActasTableAdapters.sp_listar_AcuerdosxActa_ReporteTableAdapter
                    Dim taAgendaPrelim As New dtsReporteActasTableAdapters.sp_listar_AgendaPrelimxActa_ReporteTableAdapter
                    Dim taListAge As New dtsReporteActasTableAdapters.sp_listar_AgendaxActa_ReporteTableAdapter
                    Dim taDenominacion As New dtsActaTableAdapters.usp_RecuperarDenominacionAnualTableAdapter
                    Dim taProblemas As New dtsActaTableAdapters.usp_Problema_ListarProblemaPorActaTableAdapter
                    Dim taDeConocimiento As New dtsActaTableAdapters.sp_listar_DeConocimientoxActaTableAdapter


                    Dim dtActa As New dtsReporteActas.sp_listar_ActaxActa_reporteDataTable
                    Dim dtAsistente As New dtsReporteActas.sp_listar_AsistentesxActa_ReporteDataTable
                    Dim dtAgenda As New dtsReporteActas.sp_listar_AgendaxActa_ReporteDataTable
                    Dim dtDesarrolloAgenda As New dtsReporteActas.sp_listar_DesarrolloAgendaxActa_ReporteDataTable
                    Dim dtAcuerdo As New dtsReporteActas.sp_listar_AcuerdosxActa_ReporteDataTable
                    Dim dtAgendaPrelim As New dtsReporteActas.sp_listar_AgendaPrelimxActa_ReporteDataTable
                    Dim dtListAgenda As New dtsReporteActas.sp_listar_AgendaxActa_ReporteDataTable
                    Dim dtDenominacion As New dtsActa.usp_RecuperarDenominacionAnualDataTable
                    Dim dtProblemas As New dtsActa.usp_Problema_ListarProblemaPorActaDataTable
                    Dim dtDeConomiento As New dtsActa.sp_listar_DeConocimientoxActaDataTable
                    taActa.Fill(dtActa, idActa)
                    taAsistente.Fill(dtAsistente, idActa)
                    taAgenda.Fill(dtAgenda, idActa)
                    taDesarrolloAgenda.Fill(dtDesarrolloAgenda, idActa)
                    taAcuerdo.Fill(dtAcuerdo, idActa)
                    taAgendaPrelim.Fill(dtAgendaPrelim, idActa)
                    taListAge.Fill(dtListAgenda, idActa)
                    taDenominacion.Fill(dtDenominacion)
                    taProblemas.Fill(dtProblemas, idActa)
                    taDeConocimiento.Fill(dtDeConomiento, idActa)
                    Dim rptActa As New ReportDataSource("dtsReporteActas_sp_listar_ActaxActa_reporte", CType(dtActa, DataTable))
                    Dim rptAsistente As New ReportDataSource("dtsReporteActas_sp_listar_AsistentesxActa_Reporte", CType(dtAsistente, DataTable))
                    Dim rptAgenda As New ReportDataSource("dtsReporteActas_sp_listar_AgendaxActa_Reporte", CType(dtAgenda, DataTable))
                    Dim rptDesarrolloAgenda As New ReportDataSource("dtsReporteActas_sp_listar_DesarrolloAgendaxActa_Reporte", CType(dtDesarrolloAgenda, DataTable))
                    Dim rptAcuerdo As New ReportDataSource("dtsReporteActas_sp_listar_AcuerdosxActa", CType(dtAcuerdo, DataTable))
                    Dim rptAgendaPrelim As New ReportDataSource("dtsReporteActas_sp_listar_AgendaPrelimxActa_Reporte", CType(dtAgendaPrelim, DataTable))
                    Dim rptLstAge As New ReportDataSource("dtsReporteActas_sp_listar_AgendaxActa", CType(dtListAgenda, DataTable))
                    Dim rptDenominacion As New ReportDataSource("DataSet1", CType(dtDenominacion, DataTable))
                    Dim rptProblemas As New ReportDataSource("DataSet2", CType(dtProblemas, DataTable))
                    Dim rptDeConocimiento As New ReportDataSource("DataSet3", CType(dtDeConomiento, DataTable))
                    'parametros para la cabecera
                    Dim parameters As New List(Of ReportParameter)
                    parameters.Add(New ReportParameter("rpEquipoTrabajo", dtActa.Rows(0).Item("EQUIPO").ToString(), False))
                    parameters.Add(New ReportParameter("rpArea", dtActa.Rows(0).Item("Area").ToString(), False))
                    parameters.Add(New ReportParameter("rpLugar", dtActa.Rows(0).Item("Lugar").ToString(), False))
                    parameters.Add(New ReportParameter("rpModerador", dtActa.Rows(0).Item("Moderador").ToString(), False))
                    parameters.Add(New ReportParameter("rpNumActa", dtActa.Rows(0).Item("acta_num").ToString(), False))
                    parameters.Add(New ReportParameter("rpFecha", dtActa.Rows(0).Item("fecha_Acta").ToString(), False))
                    parameters.Add(New ReportParameter("rpsemana", dtActa.Rows(0).Item("semana").ToString(), False))
                    parameters.Add(New ReportParameter("rpDuracion", dtActa.Rows(0).Item("duracion").ToString(), False))
                    parameters.Add(New ReportParameter("rpInicio", dtActa.Rows(0).Item("inicio").ToString(), False))
                    parameters.Add(New ReportParameter("rpFin", dtActa.Rows(0).Item("fin").ToString(), False))
                    'parameters.Add(New ReportParameter("rpSecretario", dtActa.Rows(0).Item("Secretario").ToString(), False))
                    parameters.Add(New ReportParameter("rpFacilitador", dtActa.Rows(0).Item("Facilitador").ToString(), False))
                    parameters.Add(New ReportParameter("anexo1", dtActa.Rows(0).Item("ANEXO_FACILITADOR").ToString(), False))
                    parameters.Add(New ReportParameter("anexo2", dtActa.Rows(0).Item("ANEXO_MODERADOR").ToString(), False))
                    'ReportViewer1.Visible = False
                    ReportViewer1.LocalReport.DataSources.Clear()
                    ReportViewer1.LocalReport.DataSources.Add(rptActa)
                    ReportViewer1.LocalReport.DataSources.Add(rptAsistente)
                    ReportViewer1.LocalReport.DataSources.Add(rptAgenda)
                    ReportViewer1.LocalReport.DataSources.Add(rptDesarrolloAgenda)
                    ReportViewer1.LocalReport.DataSources.Add(rptAcuerdo)
                    ReportViewer1.LocalReport.DataSources.Add(rptAgendaPrelim)
                    ReportViewer1.LocalReport.DataSources.Add(rptLstAge)
                    ReportViewer1.LocalReport.DataSources.Add(rptDenominacion)
                    ReportViewer1.LocalReport.DataSources.Add(rptProblemas)
                    ReportViewer1.LocalReport.DataSources.Add(rptDeConocimiento)
                    ReportViewer1.LocalReport.SetParameters(parameters)
                    'ReportViewer1.ShowPrintButton = True
                    ReportViewer1.LocalReport.Refresh()

                    'Dim warnings As Warning()
                    'Dim streamids As String()
                    'Dim mimeType As String
                    'Dim encoding As String
                    'Dim extension As String
                    'Dim bytes As Byte()
                    'bytes = ReportViewer1.LocalReport.Render("PDF", Nothing, mimeType, encoding, extension, streamids, warnings)
                    'Dim fs As FileStream

                    ''Dim archivo As String = "c:\ruta\fichero.jpg"

                    'If File.Exists(ruta & nombre) Then
                    '    My.Computer.FileSystem.DeleteFile(ruta & nombre)
                    'End If


                    'fs = New FileStream(ruta & nombre, FileMode.Create)
                    'fs.Write(bytes, 0, bytes.Length)
                    'fs.Close()
                    'Response.WriteFile("C:\Documents and Settings\jburga\Desktop\Poderosa\Poderosa\output.pdf")
                    'Response.Write("<embed src=""/AppAR/OutPut/" & nombre & """ width=""700"" height=""500""></embed>")
                Catch ex As Exception
                    Response.Write(" " & ex.Message)
                End Try
                'ShowPdf1.FilePath = "~/AppAR/OutPut/" & nombre
                'ShowPdf1.Visible = False
            End If
        End If

    End Sub

    Private Function obtenerCodigo(ByVal _id As String) As Integer
        Dim miSitio As SPSite = impersonalizar()
        'SPSite miSitio = new SPSite("http://ctovswin2k303/sites/montana");
        Dim miWeb As SPWeb = miSitio.OpenWeb()
        'SPWeb miWeb = miSitio.OpenWeb();
        Dim miLista As SPList = CType(miWeb.Lists(ConfigurationManager.AppSettings("Lista_Actas").ToString), SPList)

        '//SPList _list = (SPList)_web.Lists[ObtenerParametros(CONSTANTES.listaUsuarioSACP)];
        Dim _item As SPListItem = CType(GetItem(miLista, Convert.ToInt32(_id)), SPListItem) ';// _list.Items.GetItemById(int.Parse(_id));
        '// _item = GetItem(_list, int.Parse(ViewState["ID"].ToString()));
        Dim codigo As Integer = Convert.ToInt32(_item("ID_ACTA").ToString())
        miWeb.Close()
        miSitio.Close()
        Return codigo

    End Function

    Public Function GetItem(ByVal list As SPList, ByVal itemId As Integer) As SPListItem
        Dim query As New SPQuery()

        query.Query = "<Where><Eq><FieldRef Name=""ID""></FieldRef><Value Type=""Counter"">" + itemId.ToString() + "</Value></Eq></Where>"
        query.ViewAttributes = "Scope=""RecursiveAll"" ModerationType=""Moderator"""
        query.MeetingInstanceId = -2
        Dim collection As SPListItemCollection = list.GetItems(query)
        Return collection(0)

    End Function

    Private Function impersonalizar() As SPSite
        Dim miSite As New SPSite(ConfigurationManager.AppSettings(CONSTANTES.siteACTA))
        Dim miWeb As SPWeb = miSite.OpenWeb()
        Dim user As SPUser = miWeb.AllUsers(ConfigurationManager.AppSettings(CONSTANTES.usuarioPrivilegio))

        Dim mitoken As SPUserToken = user.UserToken
        miSite = New SPSite(ConfigurationManager.AppSettings(CONSTANTES.siteACTA), mitoken)
        Return miSite
    End Function

    Public Function verificarPermisos() As Boolean
        Dim intID As Integer = Convert.ToInt32(Request.QueryString("ID"))
        Dim Util As New utiles()
        'Dim miSite As New SPSite("http://ctovsw2k803/Poderosa")
        'Dim miWeb As SPWeb = miSite.OpenWeb()
        'Dim userPrivilegiosAltos As SPUser = miWeb.AllUsers("ctovsw2k3\administrator")
        'Dim miToken As SPUserToken = userPrivilegiosAltos.UserToken
        Dim SystemAdm As String = ConfigurationManager.AppSettings(CONSTANTES.usuarioPrivilegio)
        Dim site As SPSite = impersonalizar()
        Dim Web As SPWeb = site.OpenWeb()
        Dim lista As SPList = Web.Lists(ConfigurationManager.AppSettings(CONSTANTES.listaActas).ToString())

        Dim _item As SPListItem = lista.GetItemById(intID)
        Dim _usuActual As SPUser = Web.SiteUsers(HttpContext.Current.User.Identity.Name.ToString())
        Dim _usuAdmin As SPUser = Web.SiteUsers(SystemAdm)

        'Response.Write(_usuActual.LoginName & " " & _usuAdmin.LoginName)

        If _usuAdmin.LoginName <> _usuActual.LoginName Then
            Dim blnActivo As Boolean = False
            Dim _ColeccionRoles As SPRoleAssignmentCollection = _item.RoleAssignments
            For Each _rol As SPRoleAssignment In _ColeccionRoles
                If _rol.Member.GetType().ToString() = "Microsoft.SharePoint.SPUser" Then
                    Dim _User As SPUser = DirectCast(_rol.Member, SPUser)
                    'Response.Write(" registrado " & _User.LoginName & "<br>")
                    If _User.LoginName = _usuActual.LoginName Then
                        blnActivo = True
                        Exit For
                    End If
                ElseIf _rol.Member.GetType().ToString() = "Microsoft.SharePoint.SPGroup" Then
                    Dim groupName As String = _rol.Member.ToString()
                    Dim _Group As SPGroup = Web.SiteGroups(groupName)
                    Dim _users As SPUserCollection = _Group.Users
                    For Each _User As SPUser In _users
                        '                            Response.Write(" registrado " & _User.LoginName & "<br>")
                        If _User.LoginName = _usuActual.LoginName Then
                            blnActivo = True
                            Exit For
                        End If
                    Next
                End If
            Next

            If blnActivo = False Then
                Response.Redirect(ConfigurationManager.AppSettings("Form_Nopermitido").ToString())
                Return False
            End If

        End If
        Return True

    End Function
End Class
